<template>
	<view>
		<uv-popup ref="popupRef" mode="center" :close-on-click-overlay="false" round="20rpx" bgColor="none"
			:zIndex="10000">
			<view class="popup1">
				<uv-icon class="popup1-close" @click="closePopup()" name="close-circle" color="#FFFFFF"
					size="28"></uv-icon>
				<!-- 用于绘制海报的 canvas，默认隐藏 -->
				<image :src="posterUrl" style="width: 690rpx;height: 900rpx;border-radius: 20rpx;" mode=""></image>
				<canvas type="2d" canvas-id="posterCanvas" class="hidden-canvas"
					:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
				<!-- <view class="popup1-main">
		        <image src="@/static/icon/watermark.png" v-if="item.is_auth == 1" class="watermark" mode=""></image>
		        <image :src="item.img" class="img" mode=""></image>
		        <view class="popup1-price" v-if="item.price_type == 'fixed'">￥{{item.price}}</view>
		        <view class="popup1-price" v-else>面议</view>
				<view class="popup1-footer flex">
		          <view style="width: 365rpx;">
		            <view class="popup1-title">电话：{{item.phone}}</view>
		            <view class="popup1-add">地址：{{item.source_address}}</view>
		          </view>
		          <image :src="item.qrcode_url" class="ewm" mode=""></image>
		        </view>
		      </view> -->
				<view class="popup1-btn flex">
					<view class="btn1 flex justify-center" @click="handleShare()">分享海报</view>
					<view class="btn2 flex justify-center" @click="savePoster()">保存海报</view>
				</view>
			</view>
		</uv-popup>
		<!-- 引导页 -->
		<uv-popup ref="isGuide" mode="center" bgColor="none" :zIndex="20000" round="20rpx">
			<view class="popup2" @click="isGuide.close()">
				<image src="@/static/img/popupImg.png" mode=""></image>
			</view>
		</uv-popup>
	</view>
</template>

<script setup>
	const props = defineProps({
		item: {
			type: Object,
			default: () => {}
		}
	});
	import {
		ref,
		onMounted,
		nextTick,
	} from 'vue'
	// 弹窗引用
	const popupRef = ref(null);
	const isGuide = ref(false)

	// 关闭弹窗
	const closePopup = () => {
		if (popupRef.value) {
			popupRef.value.close();
		}
	};

	// 打开弹窗
	const openPopup = () => {
		if (popupRef.value) {
			popupRef.value.open();
		}
	};

	// 分享海报
	const handleShare = () => {
		// closePopup();
		isGuide.value.open()
	};
	const canvasWidth = ref(345); // 海报宽度
	const canvasHeight = ref(450); // 海报高度
	const posterUrl = ref(''); // 生成的海报临时路径
	
	// 加载图片资源
	const loadImage = (src) => {
	  return new Promise((resolve, reject) => {
		if (src.startsWith('https')) {
		  // 网络图片
		  uni.getImageInfo({
			src: src,
			success: (res) => {
			  resolve(res.path); // 获取成功，返回本地路径
			},
			fail: (err) => {
			  reject(err);
			}
		  });
		} else if (src.startsWith('data:image')) {
		  // Base64图片 - 需要转换为临时文件路径，示例省略，可参考前述链接原理
		  // ... (通常涉及 wx.getFileSystemManager().writeFile)
		  reject(new Error('Base64图片处理复杂，需特殊转换'));
		} else {
		  // 本地图片（static目录），在某些平台可以直接使用
		  // 但为了一致性，也建议先获取信息，或者直接使用相对路径尝试
		  resolve(src); // 或同样使用 uni.getImageInfo
		}
	  });
	}
	
	// 绘制文本（支持自动换行）
	const drawText = (ctx, text, x, y, maxWidth, lineHeight, style = {}) => {
		const { fontSize = 14, color = '#000', fontWeight = 'normal' } = style;
		  ctx.setFontSize(fontSize);
		  ctx.setFillStyle(color);
		  ctx.setTextBaseline('top');
		  
		  // 设置字体粗细
		  if (fontWeight === 'bold') {
		    ctx.font = `bold ${fontSize}px sans-serif`;
		  } else {
		    ctx.font = `normal ${fontSize}px sans-serif`;
		  }
		  
		  const words = text.split('');
		  let line = '';
		  let currentY = y;
		  
		  for (let n = 0; n < words.length; n++) {
		    const testLine = line + words[n];
		    const metrics = ctx.measureText(testLine);
		    
		    if ((metrics.width > maxWidth && n > 0) || words[n] === '\n') {
		      ctx.fillText(line, x, currentY);
		      line = words[n] === '\n' ? '' : words[n];
		      currentY += lineHeight;
		    } else {
		      line = testLine;
		    }
		  }
		  
		  if (line) {
		    ctx.fillText(line, x, currentY);
		  }
		  
		  return currentY + lineHeight;
	};
	
	// 生成海报核心逻辑 保存海报
	const generatePoster = async () => {
	  try {
	    // 加载所需图片资源
	    const loadPromises = [
	      loadImage(props.item.img),
	      loadImage(props.item.qrcode_url)
	    ];
	    
	    const images = await Promise.all(loadPromises);
	    const mainImg = images[0]; // 明确主图
	    const qrCodeImg = images[1]; // 明确二维码
	    const ctx = uni.createCanvasContext('posterCanvas');
	    
	    // 1. 绘制背景底色
	    ctx.setFillStyle('#fff');
	    ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value);
		
		// 绘制企业认证
		if(props.item.is_auth == 1) {
			ctx.drawImage('/static/icon/watermark.png', 0, 10, 65, 56);
		}
	    // 绘制产品图片 - 使用加载成功的图片路径
	    ctx.drawImage(mainImg, 20, 20, 275, 275);
	
	    // 绘制二维码及相关文本
	    const qrCodeSize = 80;
	    const qrCodeX = canvasWidth.value - 140;
	    const qrCodeY = canvasHeight.value - 100;
	    ctx.drawImage(qrCodeImg, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);
	    
	    // 绘制电话文本
	    ctx.setFontSize(14);
	    ctx.setFillStyle('#000');
	    ctx.fillText(
	      "电话：" + props.item.phone,
	      20,
	      qrCodeY + 30
	    );
	    // 绘制价格
		drawText(
		  ctx,
		  props.item.price_type == 'negotiable'? '面议' :  "￥" + props.item.price,
		  props.item.price_type == 'negotiable'? canvasWidth.value - 110 : canvasWidth.value - 130,
		  canvasHeight.value - 130,
		  canvasWidth.value - 140,
		  20, {
		    fontSize: 20,
			color: '#F83B3B'
		  }
		);
	    // 绘制地址文本
	    drawText(
	      ctx,
	       "地址：" + props.item.source_address,
	      20,
	      qrCodeY + qrCodeSize - 20,
	      canvasWidth.value - 140,
	      20, {
	        fontSize: 14
	      }
	    );
	
	    // 将canvas转换为临时文件 - 使用更兼容的写法
	    ctx.draw(false, () => {
	      // 延迟一点时间确保绘制完成
	      setTimeout(async () => {
	        const res = await uni.canvasToTempFilePath({
	          canvasId: 'posterCanvas',
	          width: canvasWidth.value,
	          height: canvasHeight.value,
	          destWidth: canvasWidth.value * 2,
	          destHeight: canvasHeight.value * 2,
	        }, this);
			posterUrl.value = res.tempFilePath;
	      }, 500);
	    });
		
	  } catch (error) {
	    console.error('生成海报失败：', error);
	    uni.showToast({
	      title: '海报生成失败，请重试',
	      icon: 'none'
	    });
	  }
	}
	
	// 保存海报
	const savePoster = () => {
		uni.showToast({
			icon: 'none',
			title: '请长按保存图片'
		})
	}
	// 暴露方法给父组件
	defineExpose({
		open: openPopup,
		close: closePopup,
		generatePoster
	});
</script>

<style lang="scss" scoped>
	.hidden-canvas {
		position: absolute;
		left: -9999rpx;
		top: -9999rpx;
	}
	
	.popup2 {
		width: 100%;
		height: 100vh;

		image {
			width: 750rpx;
			height: 100vh;
		}
	}

	.popup1 {
		width: 630rpx;

		.popup1-close {
			display: flex;
			justify-content: flex-end;
			margin-bottom: 40rpx;
		}

		.popup1-main {
			padding: 40rpx;
			box-sizing: border-box;
			border-radius: 20rpx;
			background: #FFFFFF;
			text-align: left;
			position: relative;

			.watermark {
				position: absolute;
				left: 0;
				top: 20rpx;
				width: 130rpx;
				height: 112rpx;
				z-index: 1;
			}

			.img {
				width: 550rpx;
				height: 550rpx;
				border-radius: 20rpx;
			}

			.popup1-price {
				padding: 20rpx 0;
				border-bottom: 2rpx dashed #EEEEEE;
				font-size: 40rpx;
				font-weight: bold;
				text-align: right;
				color: #F83B3B;
			}

			.popup1-footer {
				margin-top: 30rpx;

				.popup1-title {
					font-size: 26rpx;
					margin-bottom: 26rpx;
				}

				.popup1-add {
					font-size: 26rpx;
				}

				.ewm {
					border-radius: 10rpx;
					border: 2rpx solid #34A855;
					padding: 16rpx;
					margin-left: 30rpx;
					width: 128rpx;
					height: 128rpx;
				}
			}
		}

		.popup1-btn {
			margin-top: 60rpx;

			view {
				width: 300rpx;
				height: 90rpx;
				border-radius: 50rpx;
				font-size: 30rpx;
				font-weight: bold;
				color: #FFFFFF;
			}

			.btn1 {
				background: linear-gradient(270deg, #FD7D06 0%, #FFA12E 100%);
				margin-right: 30rpx;
			}

			.btn2 {
				background: linear-gradient(270deg, #39B54A 0%, #89D05F 100%);
			}
		}
	}
</style>